#!/bin/bash -e

ROOM_ID=0
CONFIG_FILE=''
CUR_DIR="$( cd "$( dirname "$0"  )" && pwd  )"
DAEMON=0
HELP=0

cd ${CUR_DIR}

while getopts "p:f:dh" opt; do  
    case $opt in  
    p)  
        echo "It will start the room: $OPTARG"
        ROOM_ID=$OPTARG
        ;;  
    f)  
        echo "the config file is: $OPTARG"
        CONFIG_FILE=$OPTARG
        ;;
    d)
        echo "It will run on daemon"
        DAEMON=1
        ;;
    h)
        HELP=1
        ;;
    \?)  
        echo "Invalid option: -$OPTARG"
        echo "start_game.sh [-d] -p roomid -f config_file \ 
        d: It can null, If the process have this argment, It is daemon. \
        p: this number tell process. It will start which room, It must be find to db. \ 
        f: config file's path, There are DB and cache confing in it."
        exit 0
        ;;  
    esac  
done

if [ ${HELP} = 1 ]
then
    echo "start_game.sh [-d] -p roomid -f config_file \ 
    d: It can null, If the process have this argment, It is daemon. \
    p: this number tell process. It will start which room, It must be find to db. \ 
    f: config file's path, There are DB and cache confing in it."
    exit 0
fi

if [ ${ROOM_ID} = 0 ]
then
   echo "roomID can be understand!"
   exit 0
fi

if [ ! -f "${CONFIG_FILE}" ]
then
    echo "the config file isn't exist."
    exit 0
fi

DAEMON_STR=''

if [ ${DAEMON} = 1 ]
then
    DAEMON_STR="-D"
fi

mkdir -p proc
mkdir -p proc/${ROOM_ID}
mkdir -p log
mkdir -p log/${ROOM_ID}

# 检查实例是否启动
sh ./check_game.sh -p ${ROOM_ID}
if [ $? = 1 ]
then
    echo "game_server ${ROOM_ID} had been running, please stop it."
    exit 0
fi

${CUR_DIR}/bin/yxj -p ${ROOM_ID} -f ${CONFIG_FILE} ${DAEMON_STR}

sleep 1s

# 检查实例是否启动
sh ./check_game.sh -p ${ROOM_ID}
if [ $? = 1 ]
then
    echo "game_server ${ROOM_ID} is running successful."
    exit 1
else
    echo "game_server ${ROOM_ID} run fail."
    exit 0
fi